/**
 * Created by 余保林 on 2017/9/11.
 */
import fs from 'fs'
import path from 'path'
import crypto from 'crypto'
import moment from 'moment'
import images from 'images'

function mapToTree (mapKey, map, key = 'id') {
	let treeList = map.get(mapKey)
	if (!treeList) {
		return []
	}
	map.delete(mapKey)
	treeList.forEach(item => {
		item.children = mapToTree('_' + item[key], map)
	})
	return treeList
}

module.exports = {
	/**
	 * 数组集合转为树
	 * @param dataList
	 * @param key
	 * @param pKey
	 * @returns {*}
	 */
	formatTree (dataList, key = 'id', pKey = 'parent_id') {
		let dataMap = new Map()
		let value = []
		dataList.forEach(data => {
			let mapKey = '_' + data[pKey]
			if (!dataMap.has(mapKey)) {
				value = []
				dataMap.set(mapKey, value)
			} else {
				value = dataMap.get(mapKey)
			}
			// data.expanded = true
			value.push(data)
		})
		return mapToTree('_0', dataMap, key)
	},
	/**
	 * 加密
	 * @param value
	 * @returns {*}
	 */
	encrypt (value) {
		const hmac = crypto.createHmac('sha256', this.config('secretKey'))
		hmac.update(value)
		return hmac.digest('hex');
	},
	/**
	 * 获取集合某一字段值的数组
	 * @param data
	 * @param field
	 * @returns {Array}
	 */
	getValueList (data, field = 'id') {
		let ids = []
		data.forEach(item => {
			ids.push(item[field])
		})
		return ids
	},
	/**
	 * 填0补位
	 * @param num
	 * @param n
	 * @returns {ArrayBuffer|Array.<T>|Blob|string}
	 */
	prefixInteger(num, n) {
		return (Array(n).join(0) + num).slice(-n);
	},
	moment,
	images,
	mkdir(dirpath, mode) {
		if (!fs.existsSync(dirpath)) {
			let pathtmp
			dirpath.split(/[/\\]/).forEach(function (dirname) {
				if (pathtmp) {
					pathtmp = path.join(pathtmp, dirname);
				}
				else {
					pathtmp = dirname;
				}
				if (!fs.existsSync(pathtmp)) {
					fs.mkdirSync(pathtmp, mode)
				}
			})
		}
	}
};